<template>
  <div class="media-picker-container">
    <q-menu 
      dense 
      ref="menuRef" 
      v-model="menuShow" 
      anchor="top middle"
      self="top middle"
      @hide="hide"
    >
      <div class="media-picker">媒体选择器</div>
      <div class="media-picker-content">{{ id }} - {{ type }}</div>
      <div class="media-picker-actions">
        <q-btn dense flat label="取消" @click="onCancel"></q-btn>
        <q-btn dense flat label="确定" color="primary" @click="onPick"></q-btn>
      </div>
    </q-menu>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { QMenu } from "quasar";

const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "",
  },
  resolve: {
    type: Function,
    default: () => {},
  },
  reject: {
    type: Function,
    default: () => {},
  },
});

const menuShow = ref(false);
const menuRef = ref<typeof QMenu>();
const isHandled = ref(false); // 标记是否已经处理过结果

const show = () => {
  console.log("show: picker is open");
  menuShow.value = true;
  isHandled.value = false; // 重置处理状态
};

const hide = () => {
  console.log("hide: picker is closed");
  menuShow.value = false;
  // 只有在没有处理过结果的情况下才调用 reject（比如点击外部区域关闭）
  if (!isHandled.value) {
    isHandled.value = true;
    props.reject(new Error('用户取消选择'));
  }
};

const onPick = () => {
  console.log("onPick: picker is pick");
  if (!isHandled.value) {
    isHandled.value = true;
    menuShow.value = false;
    props.resolve({ id: "123", url: "https://123.com" });
  }
};

const onCancel = () => {
  console.log("onCancel: picker is cancelled");
  if (!isHandled.value) {
    isHandled.value = true;
    menuShow.value = false;
    props.reject(new Error('用户取消选择'));
  }
};

defineExpose({
  show,
  hide,
});
</script>

<style scoped>
.media-picker-container {
  position: relative;
}

.media-picker {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 300px;
}

.media-picker-content {
  padding: 10px;
  margin: 10px 0;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.media-picker-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 10px 0 0 0;
}
</style>